# -*- coding: utf8 -*-
import requests
import json
import asyncio
import time

from httpx import AsyncClient

with open("config.json","r") as f:
    data = json.load(f)
    cookies = data["cookies"]
    gid = data["gid"]

def cookie_to_dic(cookie):
    cookie_dic = {}
    for i in cookie.split('; '):
        cookie_dic[i.split('=')[0]] = i.split('=')[1]
    return cookie_dic

def convert_cookies_to_dict(cookie):
    cookieDict = {}
    cookies = cookie.split("; ")
    for co in cookies:
        co = co.strip()
        p = co.split('=')
        value = co.replace(p[0]+'=', '').replace('"', '')
        cookieDict[p[0]]=value
    return cookieDict


def Bkn(Skey):
    t = 5381
    n = 0
    o = len(Skey)
    while n < o:
        t += (t << 5) + ord(Skey[n])
        n += 1
    return t & 2147483647

def Headers(cookies,gid):
    headers = {
    'Host': 'qun.qq.com',
    'accept': 'application/json, text/plain, */*',
    'user-agent': 'Mozilla/5.0 (Linux; Android 7.0; MI NOTE Pro Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.72 MQQBrowser/6.2 TBS/045806 Mobile Safari/537.36 V1_AND_SQ_8.8.20_1976_YYB_D A_8082000 QQ/8.8.20.5865 NetType/WIFI WebP/0.3.0 Pixel/1440 StatusBarHeight/73 SimpleUISwitch/0 QQTheme/1000 InMagicWin/0 StudyMode/0 CurrentMode/0 CurrentFontScale/1.0',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': f'https://qun.qq.com/homework/qunsolitaire/list.html?_wv=1031&gc={gid}',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'cookie': cookies,
    'q-ua2': 'QV=3&PL=ADR&PR=QQ&PP=com.tencent.mobileqq&PPVN=8.8.20&TBSVC=44069&CO=BK&COVC=045806&PB=GE&VE=GA&DE=PHONE&CHID=0&LCID=9422&MO= MINOTEPro &RL=1440*2560&OS=7.0&API=24',
    'q-guid': 'ec157ab657a76d2d019aa64c13b788cb',
    'q-qimei': '',
    'q-auth': '31045b957cf33acf31e40be2f3e71c5217597676a9729f1b'
    }
    return headers

def CidList(cookies,gid,bkn):
    url = "https://qun.qq.com/cgi-bin/group_chain/chain_list"
    headers = Headers(cookies=cookies,gid=gid)
    params= {
    'gc':gid,
    'start':'0',
    'num':'10',
    'bkn':bkn
    }
    cids = requests.get(url=url,headers=headers,params=params)
    cids = json.loads(cids.text)['data']['list']
    id_lst=[]
    for cid in cids:
        id=cid['id']
        id_lst.append(id)
    return id_lst

dict_cookie = convert_cookies_to_dict(cookies)
skey = dict_cookie["skey"]
bkn = Bkn(skey)
url = "https://qun.qq.com/cgi-bin/group_chain/chain_sign"
headers = Headers(cookies=cookies,gid=gid)

print(f"开始监测{gid}的群接龙事件...")
print("请不要关闭,若出现Success即为成功...")

async def getReq2():
    while True:
        try:
            async with AsyncClient() as client:
                cids = CidList(cookies=cookies,gid=gid,bkn=bkn)
                for cid in cids:
                    params= {
                    'gc':gid,
                    'cid':cid,
                    'bkn':bkn
                    }
                    req = await client.get(url=url, headers=headers, params=params)
                    msg = json.loads(req.text)
                    if msg["retcode"] == 0:
                        print(f'Success:{cid}           {time.ctime()}')
        except Exception as e:
            print("请求失败", e)


if __name__ == '__main__':
    tasks = [getReq2() for _ in range(8)]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
